/****
 * obj：查询条件数组，
 * setObj:更新对象，
 * update返回[更新条数]，更新失败为[0]
 * find返回数据对象, 查询不到为[]
 * add返回插入的对象数据
 * del返回删除的数量，删除失败为 0
 */


//增加
const add = (model, obj) => {
  return new Promise((resolve, reject) => {
    model.create(obj)
      .then((data) => {
        resolve(data.dataValues)
      })
      .catch(err => {
        reject(err)
      })
  })
}

// 批量增加
const addAll = (model, arr) => {
  return new Promise((resolve, reject) => {
    model.bulkCreate(arr)
      .then((data) => {
        resolve(data.dataValues)
      })
      .catch(err => {
        reject(err)
      })
  })
}


//查找数据
const find = (model, obj = {}) => {
  return new Promise((resolve, reject) => {
    model.findAll({
      where: obj
    })
      .then((data) => {
        resolve(data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

// 更新数据
const update = (model, setObj, obj) => {
  return new Promise((resolve, reject) => {
    model.update(setObj, {
      where: obj
    })
      .then((data) => {
        resolve(data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

//删除
const del = (model, obj) => {
  return new Promise((resolve, reject) => {
    model.destroy({
      where: obj
    })
      .then((data) => {
        resolve(data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

// 删除全部数据
const delAll = (model) => {
  return new Promise((resolve, reject) => {
    model.destroy({
      where: {},
      truncate: true
    })
      .then((data) => {
        resolve(data)
      })
      .catch(err => {
        reject(err)
      })
  })
}





module.exports = {
  add, find, update, del, addAll, delAll
}